#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/wait.h>


#define COMMAND_SIZE 100
#define FORMAT "[%s@%s %s]# "
#define ARGV_SIZE 12

extern char** environ;

void PrintCommandPrompt()
{
	char command[COMMAND_SIZE];
	const char* user = getenv("USER");
	//printf("%s\n",user);
	if (user==nullptr)
		user ="None";
	const char* hostname = getenv("HOSTNAME");
	//printf("%s\n",hostname);
	if (hostname==nullptr)
		hostname ="None";
	const char* pwd = getenv("PWD");
	//printf("%s\n",pwd);
	if (pwd==nullptr)
		pwd ="None";
	snprintf(command, sizeof(command), FORMAT, user, hostname, pwd);
	printf("%s",command);
	fflush(stdout);
}

void GetCommand(std::vector<std::string>& commend)
{
    //char str[COMMAND_MAX_SIZE] = { 0 };
    //std::string strcommand(fgets(str, COMMAND_MAX_SIZE, stdin));
    std::string str;
    std::string cinstr;
    std::getline(std::cin, cinstr);
    for (auto it : cinstr)
    {
        if (it == ' ')
        {
            commend.push_back(move(str));
        }
        else
        {
            str.push_back(it);
        }
    }
    commend.push_back(move(str));
}

void MyFork(std::vector<std::string>& commend)
{
	char* argv[ARGV_SIZE] = { NULL };
	int i=0;
	for(i=0;i<commend.size();i++)
	{
		argv[i] = (char*)commend[i].c_str();
	}
	argv[i]=NULL;

	pid_t childid = fork();
	if(childid==0)
	{
//	        printf("I am Child, My Pid Is: %d\n", getpid());
        	execvpe("/usr/bin/ls", argv, environ);
		exit(1);
    	}
      	waitpid(-1, NULL, 0);
}

int main()
{
	std::vector<std::string> mycommand;
	while(1)
	{
		//打印命令行格式
		PrintCommandPrompt();
		
		//获取解析命令
		GetCommand(mycommand);
		
		//调用子进程
		for (auto it : mycommand)
		{
		     printf("%s ", it.c_str());
		}
		printf("\n");
		MyFork(mycommand);
	 	//waitpid(-1, NULL, 0);	
 		//exit退出

		mycommand.clear();
	}
	
	return 0;
}

